﻿var body = null;
var pop = null;

function installListener() {
	body = document.getElementsByTagName("body")[0];
	body.addEventListener("mouseup", onMouseUp, false);
}

setTimeout( installListener, 100 );

function onMouseUp(e) {
    var word = getSelectedWord();

    if (word != '') {
        chrome.extension.sendRequest({ query: "username" }, 
        function(response) {
        console.log("get user: " + response.username);
        showPopUp(word, response.username, window.getSelection().getRangeAt(0).startContainer.nodeValue, e.pageX, e.pageY, e.screenX, e.screenY);
        }
        );
    } else {
        hidePopUp();
    }
}

function hidePopUp() {
    if (pop) {
        pop.style.display = "none";
    }
}

function showPopUp(word, u, senctence, x, y, screenX, screenY) {
    var pop_height = 122;
    var pop_width = 302;
    var padding = 10;

    var pop_left = 0;
    var pop_top = 0;

    if (!pop) {
        pop = document.createElement('iframe');
        hidePopUp();
        body.appendChild(pop);
    }

    var src = chrome.extension.getURL("float.html") + "?word=" + word;
    if (u) {
        src += "&user=" + u;
    }
    pop.src = src;
    var screen_width = screen.availWidth;
    var screen_height = screen.availHeight;

    if (screenX + pop_width < screen_width) {
        pop_left = x;
    } else {
        pop_left = (x - pop_width - 2 * padding);
    }
    pop.style.left = pop_left + 'px';

    if (screenY + pop_height + 20 < screen_height) {
        pop_top = y;
    } else {
        pop_top = (y - pop_height - 2 * padding);
    }
    pop.style.top = pop_top + 'px';

    pop.style.position = 'absolute';
    pop.style.height = pop_height + 'px';
    pop.style.width = pop_width + 'px';
    pop.style.border = '1px solid #767676';
    pop.style.zIndex = '65535';
    pop.scrolling = "auto";
    pop.style.display = "block";
}

function getSelectedWord() {
    var selection = window.getSelection();
    console.log("selection: " + selection.toString());
    if (!selection) {
        return "";
    }

    var word = selection.toString();
    console.log("word: " + word);
    word = word.replace(/^\s*/, "").replace(/\s*$/, "");
    console.log("word normalized: " + word);

    if (word.length > 36) {
        return "";
    }

    return word;
}
